import "./login.scss"
import React, { useState } from 'react'
import {
    Form,
    Input,
    Button,
    Toast
} from 'antd-mobile'
import { EyeInvisibleOutline, EyeOutline } from 'antd-mobile-icons'
import { useDispatch } from "react-redux"
import { fetchUser } from "@/store/modules/userSlice"
import { useNavigate } from "react-router-dom"

function Login() {
    const dispatch = useDispatch()
    const navigate = useNavigate()

    const onFinish = (values) => {
        dispatch(fetchUser(values)).then(() => {
            navigate("/")
        })
    }
    const onFinishFailed = ({ values, errorFields, outOfDate }) => {
        errorFields.forEach(item => {
            Toast.show({
                content: item.errors,
                position: 'bottom',
            })
        })
    }
    const [visible, setVisible] = useState(false)

    return (
        <div className="login">
            <Form
                initialValues={{
                    name: "lzz",
                    password: "lzz011212"
                }}
                onFinish={onFinish}
                onFinishFailed={onFinishFailed}
                layout='horizontal'
                footer={
                    <Button block type='submit' color='primary' size='large'>
                        登录
                    </Button>
                }
            >
                <Form.Item
                    name='name'
                    label='姓名'
                    rules={[{ required: true, message: '姓名不能为空' }]}
                >
                    <Input clearable placeholder='请输入姓名' />
                </Form.Item>
                <Form.Item
                    label='密码'
                    name='password'
                    rules={[{ required: true, message: '密码不能为空' }]}
                    extra={
                        <div>
                            {!visible ? (
                                <EyeInvisibleOutline onClick={() => setVisible(true)} />
                            ) : (
                                <EyeOutline onClick={() => setVisible(false)} />
                            )}
                        </div>
                    }
                >
                    <Input
                        placeholder='请输入密码'
                        clearable
                        type={visible ? 'text' : 'password'}
                    />
                </Form.Item>
            </Form>
        </div>
    )
}

export default Login